package com.sde.interceptor;

import cn.hutool.core.util.StrUtil;
import com.sde.Constant.ConstantRes;
import com.sde.Enum.ResponseCodeEnum;
import com.sde.exception.BusinessException;
import com.sde.utils.JwtUtils;
import com.sde.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1，获取请求的url
        String url = request.getRequestURL().toString();
        //2，判断请求头中是否包含 login，包含login就放行(也可以不写)
        if (url.contains("/login")){
            return true;
        }
        //3，获取请求头中的token
        String token = request.getHeader("Authorization");
        //4，判断令牌是否存在
        if ((StrUtil.isEmpty(token))){
            log.info("请求中没有携带令牌");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BusinessException(ResponseCodeEnum.NOT_TOKEN);
        }

        //5，解析token
        Claims claims = null;
        try {
           claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌解析出错");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6，解析出来的token放到ThreadLocal中
        ThreadLocalUtil.set(claims.get(ConstantRes.USERID));
        //7，放行
        return true;

    }
}
